import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { authInterceptor } from './auth.interceptor'

const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'

const request = axios.create({
  baseURL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 应用拦截器
const { requestInterceptor, responseInterceptor, errorInterceptor } = authInterceptor()

request.interceptors.request.use(requestInterceptor)
request.interceptors.response.use(responseInterceptor, errorInterceptor)

// 封装常用请求方法
export const http = {
  get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return request.get(url, config).then(response => response.data)
  },

  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return request.post(url, data, config).then(response => response.data)
  },

  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return request.put(url, data, config).then(response => response.data)
  },

  delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return request.delete(url, config).then(response => response.data)
  }
}

export default request
